package com.husd.leetcode.string;

/**
 * https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
 * <p>
 * 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如，输入字符串"abcdefg"和数字2，该函数将返回左旋转两位得到的结果"cdefgab"。
 * <p>
 *  
 * <p>
 * 示例 1：
 * <p>
 * 输入: s = "abcdefg", k = 2
 * 输出: "cdefgab"
 * 示例 2：
 * <p>
 * 输入: s = "lrloseumgh", k = 6
 * 输出: "umghlrlose"
 *  
 * <p>
 * 限制：
 * <p>
 * 1 <= k < s.length <= 10000
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @author hushengdong
 */
public class ReverseLeftWords {

    public String reverseLeftWords(String s, int n) {

        int len = s.length();
        n = n % len;
        if (n == 0) {
            return s;
        }
        StringBuilder res = new StringBuilder(len);
        for (int i = n; i < len; i++) {
            res.append(s.charAt(i));
        }
        for (int i = 0; i < n; i++) {
            res.append(s.charAt(i));
        }
        return res.toString();
    }

    public String reverseLeftWords2(String s, int n) {

        //编程珠玑第2章算法
        char[] arr = s.toCharArray();
        int len = s.length();
        reverse(arr, 0, n - 1);
        reverse(arr, n, len - 1);
        reverse(arr, 0, len - 1);
        return String.valueOf(arr);
    }

    //反转这个数组，从start开始，到end结束，包含start和end
    public void reverse(char[] arr, int start, int end) {

        while (start < end) {

            char c = arr[start];
            arr[start] = arr[end];
            arr[end] = c;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {

        ReverseLeftWords reverseLeftWords = new ReverseLeftWords();
        char [] arr = {'a','b','c','d','e','f','g'};
        int n = arr.length;
        reverseLeftWords.reverse(arr, 0, n - 1);
        System.out.println(String.valueOf(arr));

        String s = reverseLeftWords.reverseLeftWords2("abcdefgh",3);
        System.out.println(s);
    }


}
